#define  _CRT_SECURE_NO_WARNINGS
class Solution {
    int rob(vector<int>& f)
    {
        int n = f.size();
        vector<int> g(n);
        for (int i = 1; i < n; i++)
        {
            f[i] = g[i - 1] + f[i];
            g[i] = max(g[i - 1], f[i - 1]);
        }
        return max(f[n - 1], g[n - 1]);
    }
public:
    int deleteAndEarn(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        int n = nums.size();

        vector<int> tmp(n * 2);
        int index = 0;
        int prev = nums[0];
        for (int i = 0; i < n; i++)
        {
            if (nums[i] == prev)
            {
                tmp[index] += prev;
            }
            else
            {
                if (prev == nums[i] - 1) tmp[++index] += (prev = nums[i]);
                else tmp[index += 2] += (prev = nums[i]);
            }
        }

        return rob(tmp);
    }
};